What is one and what is the other one?
Before digging more inside the subject of learning C++ you should know with what you are dealing inside your programs.
As you could see in the opening page of this chapter, functions come handy when dealing with large amount o code. This code should be splited into small blocs that are specialized into doing something.
A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.
Example:
class Rectangle
{
int width, height;
public:
void set_values (int a,int b)
{
width = a;
height = b;
}
int area (void)
{
return width*height;
}
};
int main()
{
Rectangle r = Rectangle();
r.set_values(3,5);
int area = r.area();
}
As you can see in this example there are two such kind of specialized blocks of code.
All the work that this two blocks of code are doing is related to an object. This is how the methods can be distinguished from functions.
A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).
All data that is passed to a function is explicitly passed.
Example:
Now lets translate earlier example into function based program. Please note that functions aren't related to an object, they only can live along an object as a static function (we'll get later on this subject), so we're not going to need anymore the class Rectangle.
int area(int width, int height)
{
return width*height;
}
int main()
{
int area = area(3,5);
}
You should probably have in mind one question: Why we are using Object Oriented programming since the code is much simpler with standard function programming?
The answer is very simple: maybe in this case the the program is much simpler using non-object oriented programming but I can assure you that when you're dealing with much more complicated logic object oriented stuff comes more handy to use.